<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      @open="onOpen"
      @close="onClose"
      title="编辑版头图"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="default"
        label-width="100px"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入标题"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传" prop="imgUrl" required>
              <el-upload
                ref="imgUrl"
                v-model:file-list="imgUrlfileList"
                :action="imgUrlAction"
                :headers="headers"
                :before-upload="imgUrlBeforeUpload"
                :limit="1"
                list-type="picture-card"
                :on-success="handleUploadSuccess"
                :on-preview="handlePictureCardPreview"
                accept="image/*"
                :on-remove="handleRemove"
                :class="{ hide: hideUpload }"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转链接" prop="link">
              <el-input
                v-model="formData.link"
                placeholder="请输入跳转链接"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                placeholder="请输入排序"
                clearable
                :style="{ width: '100%' }"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="imgType">
              <el-select
                v-model="formData.imgType"
                placeholder="请选择活动类型"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="item in proTypeOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
  <el-dialog v-model="imgDialogVisible">
    <img class="w-full" :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import useActivityStore from "@/store/modules/activity";
import { getActivityTypeBanner } from "@/api/system/banner";

const headers = ref({
  Authorization: "Bearer " + getToken(),
});

const { proxy } = getCurrentInstance();
const formRef = ref();
const proTypeOptions = ref([]);
const props = defineProps({
  currentBanner: { type: Object, default: {} },
});
const imgDialogVisible = ref(false);
const dialogImageUrl = ref("");
const data = reactive({
  formData: {
    title: "",
    imgUrl: null,
    link: "",
    sort: 0,
    imgType: "",
  },
  rules: {
    title: [
      {
        required: true,
        message: "请输入标题",
        trigger: "blur",
      },
    ],
    link: [
      {
        required: true,
        message: "请输入跳转链接",
        trigger: "blur",
      },
    ],
    sort: [
      {
        required: true,
        message: "请输入排序",
        trigger: "blur",
      },
    ],
    imgType: [
      {
        required: true,
        message: "请选择类别",
        trigger: "blur",
      },
    ],
  },
});
const { formData, rules } = toRefs(data);
// 上传请求路径
const imgUrlAction = ref(import.meta.env.VITE_APP_BASEURL + "/common/upload");
// 上传文件列表
const imgUrlfileList = ref([]);
const hideUpload = ref(false);
const limitCount = ref(1);
/**
 * @name: 上传之前的文件判断
 * @description: 上传之前的文件判断，判断文件大小文件类型等
 * @param {*} file
 * @return {*}
 */
function imgUrlBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 2000;
  if (!isRightSize) {
    proxy.$modal.msgError("文件大小超过 2G");
  }
  return isRightSize;
}
// 弹窗设置
const dialogVisible = defineModel();
// 弹窗确认回调
const emit = defineEmits(["confirm"]);
/**
 * @name: 弹窗打开后执行
 * @description: 弹窗打开后执行方法
 * @return {*}
 */
async function onOpen() {
  // proTypeOptions.value = await useActivityStore().getType();
  await getBannerType();
  if (props.currentBanner.id) {
    getList();
  }
}
//修改时初始化
function getList() {
  formData.value.title = props.currentBanner.title;
  formData.value.imgType = props.currentBanner.imgType;
  formData.value.link = props.currentBanner.link;
  formData.value.sort = props.currentBanner.sort;
  formData.value.imgUrl = props.currentBanner.imgUrl;
  imgUrlfileList.value.push({
    name: "轮播图",
    url: props.currentBanner.imgUrl,
  });
  hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
}
async function getBannerType() {
  await getActivityTypeBanner().then((res) => {
    proTypeOptions.value = res.data.records;
  });
}
/**
 * @name: 弹窗关闭时执行
 * @description: 弹窗关闭方法，重置表单
 * @return {*}
 */
function onClose() {
  formRef.value.resetFields();
  formData.value.title = "";
  formData.value.imgType = "";
  formData.value.link = "";
  formData.value.sort = 0;
  formData.value.imgUrl = "";
  imgUrlfileList.value = [];
  hideUpload.value = false;
}
/**
 * @name: 弹窗取消
 * @description: 弹窗取消方法
 * @return {*}
 */
function close() {
  dialogVisible.value = false;
}
function handleUploadSuccess(res) {
  if (res) {
    formData.value.imgUrl = res.fullurl;
    hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
  }
}
//图片放大
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  imgDialogVisible.value = true;
};
//缩略图删除
const handleRemove = (res) => {
  formData.value.imgUrl = "";
  hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
};
/**
 * @name: 弹窗表单提交
 * @description: 弹窗表单提交方法
 * @return {*}
 */
function handelConfirm() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    // TODO 提交表单
    close();
    // 回调父级组件
    emit("confirm", formData.value);
  });
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
